package leetcode.hot100;

@SuppressWarnings("all")
public class _200_岛屿数量 {

    // 给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量
    // 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成
    // 此外，你可以假设该网格的四条边均被水包围

    /**
     * 输入：grid = [
     * ["1","1","1","1","0"],
     * ["1","1","0","1","0"],
     * ["1","1","0","0","0"],
     * ["0","0","0","0","0"]
     * ]
     * 输出：1
     */
    int count = 0;
    char[][] grid;

    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        this.grid = grid;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                // 只要找到一块陆地，就将陆地的相邻陆地全部标记
                if (grid[i][j] == '1') {
                    dfs(i, j);
                    // 相邻的陆地连成一块岛屿
                    count++;
                }
            }
        }
        return count;
    }

    void dfs(int row, int clo) {
        // 判断 base case
        // 如果坐标 (row, clo) 超出了网格范围，直接返回
        if (!inArea(row, clo)) {
            return;
        }

        // 如果这个格子不是岛屿，直接返回
        if (grid[row][clo] != '1') {
            return;
        }
        // 将格子标记为「已遍历过」
        grid[row][clo] = '2';

        // 访问上、下、左、右四个相邻结点
        dfs(row - 1, clo);
        dfs(row + 1, clo);
        dfs(row, clo - 1);
        dfs(row, clo + 1);
    }

    // 判断坐标 (row, clo) 是否在网格中
    boolean inArea(int row, int clo) {
        return 0 <= row && row < grid.length
                && 0 <= clo && clo < grid[0].length;
    }
}
